<template>
  <div class="infoWrapper">
    <div class="info">
      <div class="left">
        <div class="left_part1" style="display: flex; margin-bottom: 15px">
          <div class="infoItem">
            <div>中心：</div>
            <el-select v-model="centers.activeItem" placeholder="中心">
              <el-option
                v-for="item in centers.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="infoItem">
            <div>角色选择：</div>
            <el-select v-model="roles.activeItem" placeholder="角色">
              <el-option
                v-for="item in roles.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="infoItem">
            <div>高频指令：</div>
            <el-checkbox
              v-model="highInstructSelect.check1"
              label="是"
              size="large"
            />
            <el-checkbox
              v-model="highInstructSelect.check2"
              label="否"
              size="large"
            />
          </div>
          <div class="infoItem">
            <div>开启状态：</div>
            <el-checkbox
              v-model="switchStateSelect.open"
              label="是"
              size="large"
            />
            <el-checkbox
              v-model="switchStateSelect.close"
              label="否"
              size="large"
            />
          </div>
          <div class="infoItem">
            <div>是否对外展示：</div>
            <el-checkbox v-model="displaySelect.open" label="是" size="large" />
            <el-checkbox
              v-model="displaySelect.close"
              label="否"
              size="large"
            />
          </div>
        </div>

        <div class="left_part2" style="display: flex">
          <div class="infoItem">
            <div>设备：</div>
            <el-select v-model="inputDevice.activeItem">
              <el-option
                v-for="item in inputDevice.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <div class="infoItem">
            <div>交互方式：</div>
            <el-select v-model="instructTypeSelect.activeItem">
              <el-option
                v-for="item in instructTypeSelect.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="infoItem">
            <div>学年阶段：</div>
            <el-select v-model="version.activeItem" placeholder="学年阶段">
              <el-option
                v-for="item in version.data"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <div class="infoItem">
            共<span>{{ instructSum }}</span
            >条指令
          </div>
        </div>
      </div>

      <div class="right">
        <el-select
          v-model="search.activeItem"
          class="infoItem"
          style="width: 170px"
        >
          <el-option
            v-for="item in search.data"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="searchInstructStr"
          placeholder="模块/指令名/模块ID/指令关键词"
          class="input infoItem"
          clearable
          @keyup.enter.native="searchInstruct"
          @clear="searchInstruct"
        >
          <template #append>
            <el-button :icon="Search" @click="searchInstruct" />
          </template>
        </el-input>
        <el-button
          type="primary"
          class="createBtn infoItem"
          @click="props.openDraw"
          >新增标准指令</el-button
        >
        <el-button @click="exportInstruct"> 导出 </el-button>
      </div>
    </div>
    <div class="content">
      <slot
        :tableData="tableData"
        :deleteInstructs="deleteInstructs"
        :refresh="refresh"
        :changeInstructOpenType="changeInstructOpenType"
        :changeInstructIsHigh="changeInstructIsHigh"
        :changeInstructDisplay="changeInstructDisplay"
        :addInstructDescribe="addInstructDescribe"
      ></slot>
    </div>
  </div>
</template>
<script setup>
import {
  api_addInstructDescribe,
  getInstructs,
  removeInstructs,
  api_instructExport
} from "@/api/manage";
import { Search } from "@element-plus/icons-vue";
import { ElLoading, ElMessage } from "element-plus";
import { onMounted, reactive, ref, watch } from "vue";
import {
  ECenter,
  centerSelectData,
  roleSelectData,
  searchTypeData,
} from "../enum";

const props = defineProps({
  openDraw: Function,
  lastDownloadTime: String,
});

// 按中心搜索
const centers = reactive({
  data: [...centerSelectData, { label: "全部中心", value: "all" }],
  activeItem: "Z",
});
// 按角色搜索
const roles = reactive({
  data: [{ label: "全部角色", value: "all" }, ...roleSelectData],
  activeItem: "all",
});
// 按学年阶段搜索
const version = reactive({
  data: [
    { label: "全部阶段", value: "7" },
    { label: "中小学", value: "2" },
    { label: "大学", value: "1" },
    { label: "中职", value: "4" },
  ],
  activeItem: "7",
});
// 按学年阶段搜索
const inputDevice = reactive({
  data: [
    { label: "全部设备", value: "all" },
    { label: "PC端", value: "1" },
    { label: "移动端", value: "2" },
  ],
  activeItem: "all",
});
// 按交互方式搜索
const instructTypeSelect = reactive({
  data: [
    { label: "全部方式", value: "all" },
    { label: "数据返回", value: "DATA_RETURN" },
    { label: "打开操作", value: "OPEN_OPERATION" },
    { label: "控制操作", value: "CONTROL_OPERATION" },
    { label: "推荐指令", value: "RECOMMEND_INSTRUCT" },
  ],
  activeItem: "all",
});
// 高频指令搜索
const highInstructSelect = reactive({
  check1: false,
  check2: false,
});

// 【开启状态】搜索
const switchStateSelect = reactive({
  open: true,
  close: false,
});

//【是否对外展示】搜索
const displaySelect = reactive({
  open: true,
  close: true,
});

// 按名称搜索
const search = reactive({
  data: searchTypeData,
  activeItem: "instructName",
});
const instructSum = ref(0);
const searchInstructStr = ref("");
const tableData = ref([]);

const changeInstructOpenType = (code) => {
  tableData.value?.forEach((center) => {
    center.robotInstructModuleDTOS?.forEach((curModule) => {
      curModule.robotInstructNameAndSentenceDTOS?.forEach((instruct) => {
        if (instruct.instructCode === code) {
          instruct.flag = instruct.flag === 0 ? 1 : 0;
        }
      });
    });
  });
};

const changeInstructIsHigh = (code) => {
  tableData.value?.forEach((center) => {
    center.robotInstructModuleDTOS?.forEach((curModule) => {
      curModule.robotInstructNameAndSentenceDTOS?.forEach((instruct) => {
        if (instruct.instructCode === code) {
          instruct.isHigh = instruct.isHigh === "0" ? "1" : "0";
        }
      });
    });
  });
};

const changeInstructDisplay = (code) => {
  tableData.value?.forEach((center) => {
    center.robotInstructModuleDTOS?.forEach((curModule) => {
      curModule.robotInstructNameAndSentenceDTOS?.forEach((instruct) => {
        if (instruct.instructCode === code) {
          instruct.display = instruct.display === "0" ? "1" : "0";
        }
      });
    });
  });
};

const refresh = () => {
  fetchInstruct({});
};

defineExpose({ refresh });

onMounted(() => {
  // 通过Manage的mounted后调用此方法
  // refresh();
});

const fetchInstruct = async (d) => {
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "transparent",
  });

  d.centerName = centers.activeItem;
  d.role = roles.activeItem;
  d.version = version.activeItem;
  d.inputDevice = inputDevice.activeItem;
  d.instructType = instructTypeSelect.activeItem;

  if (d.centerName === "all") {
    delete d.centerName;
  }
  if (d.role === "all") {
    delete d.role;
  }
  if (d.inputDevice === "all") {
    delete d.inputDevice;
  }
  if (d.instructType === "all") {
    delete d.instructType;
  }
  d.centerName = ECenter[d.centerName];

  // 设置isHigh
  if (highInstructSelect.check1) {
    d.isHigh = 1;
  }
  if (highInstructSelect.check2) {
    if (d.isHigh === 1) {
      delete d.isHigh;
    } else {
      d.isHigh = 0;
    }
  }

  if (switchStateSelect.open) {
    d.isDeleted = 0;
  }
  if (switchStateSelect.close) {
    if (d.isDeleted === 0) {
      delete d.isDeleted;
    } else {
      d.isDeleted = 1;
    }
  }

  if (displaySelect.open) {
    d.display = 1;
  }
  if (displaySelect.close) {
    if (d.display === 1) {
      delete d.display;
    } else {
      d.display = 0;
    }
  }

  try {
    const { data, success, msg } = await getInstructs({
      ...d,
      [search.activeItem]: searchInstructStr.value,
    });
    if (!success) {
      throw new Error("获取指令失败,接口返回:" + msg);
    }
    tableData.value = data;
    let sum = 0;
    data.forEach((v) => {
      v.robotInstructModuleDTOS.forEach((v1) => {
        sum += v1.robotInstructNameAndSentenceDTOS.length;
      });
    });
    instructSum.value = sum;
  } catch (e) {
    ElMessage.error("获取数据失败");
  }
  loading.close();
};

const deleteInstructs = async (index, row) => {
  const r = await removeInstructs({
    instructCode: row.instructCode,
    instructName: row.instructName,
    flag: row.flag,
  });
  if (r.success === true) {
    ElMessage.success(`${row.instructName}指令(${row.instructCode})删除成功`);
    fetchInstruct({});
  } else {
    ElMessage.error(
      `${row.instructName}指令(${row.instructCode})删除失败,接口返回:${r.msg}`
    );
  }
};

/**
 * 新增指令的备注
 *
 * @param {*} row 指令对象
 */
const addInstructDescribe = async (row) => {
  const r = await api_addInstructDescribe({
    instructCode: row.instructCode,
    describe: row.describe,
  });
  if (r.success === true) {
    ElMessage.success(`备注成功`);

    // 设置指令的备注
    tableData.value?.forEach((center) => {
      center.robotInstructModuleDTOS?.forEach((curModule) => {
        curModule.robotInstructNameAndSentenceDTOS?.forEach((instruct) => {
          if (instruct.instructCode == row.instructCode) {
            instruct.describe = row.describe;
          }
        });
      });
    });
  } else {
    ElMessage.error(
      `${row.instructName}指令(${row.instructCode})备注失败,接口返回:${r.msg}`
    );
  }
};

const exportInstruct = async () => {
  let r = null;
  await api_instructExport()
    .then((res) => {
      r = res;
    })
    .catch((err) => {});

  const a = document.createElement("a");
  const url = window.URL.createObjectURL(r);
  a.href = url;
  a.download = "人工智能机器人-指令.xlsx"; //这里最重要。如果不加后缀。保存的文件就会异常或者乱码。一定要写文件后缀类型
  a.click();
};

const emits = defineEmits(["visibleChange"]);

const searchInstruct = () => {
  refresh();
};
watch(
  () => centers.activeItem,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => roles.activeItem,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => version.activeItem,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => inputDevice.activeItem,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => instructTypeSelect.activeItem,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => highInstructSelect.check1,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => highInstructSelect.check2,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => switchStateSelect.open,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => switchStateSelect.close,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => displaySelect.open,
  (newVal) => {
    fetchInstruct({});
  }
);
watch(
  () => displaySelect.close,
  (newVal) => {
    fetchInstruct({});
  }
);
</script>

<style lang="scss" scoped>
.infoWrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .info {
    margin: 15px 30px 20px 30px;
    display: flex;
    justify-content: space-between;
    :deep(.el-select) {
      width: 130px;
    }
    .infoItem {
      display: flex;
      align-items: center;

      .el-checkbox {
        margin-right: 10px;
        margin-top: 1px;
      }
    }
    .infoItem + .infoItem {
      margin-left: 20px;
    }
    .left {
      display: flex;
      flex-direction: column;

      font-weight: 600;
      font-size: 17px;
      color: #555555;
    }
    .right {
      display: flex;
      align-items: flex-start;
      .input {
        width: 350px;
      }
      .createBtn {
      }
      :deep() {
        .el-select__wrapper {
          width: 100%;
        }
      }
    }
  }
  .content {
    flex: 1;
    min-height: 0;

    box-shadow: 0 1px 6px #0000001a;
    padding: 15px 0;
  }
}
</style>
